package com.example.jpa.crud.controller;

import com.example.jpa.crud.service.SimpleCrudService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

@RestController
public class SimpleCrudControllerForSpringBoot3 {

    private static final Logger log = LoggerFactory.getLogger(SimpleCrudControllerForSpringBoot3.class);

    private final SimpleCrudService simpleCrudService;

    public SimpleCrudControllerForSpringBoot3(SimpleCrudService simpleCrudService) {
        this.simpleCrudService = simpleCrudService;
    }

    @PostMapping("{resource}")
    public Object create(@PathVariable("resource") String resource, HttpServletRequest request) {
        byte[] data;
        try {
            data = StreamUtils.copyToByteArray(request.getInputStream());
        } catch (IOException e) {
            log.error("create", e);
            return null;
        }
        return simpleCrudService.create(resource, data);
    }

    @GetMapping("{resource}/{id}")
    public Object findById(@PathVariable("resource") String resource, @PathVariable("id") String id) {
        return simpleCrudService.findById(resource, id);
    }

    @GetMapping("{resource}")
    public Object search(@PathVariable("resource") String resource, HttpServletRequest request) {
        final Map<String, String[]> parameterMap = request.getParameterMap();
        return simpleCrudService.search(resource, parameterMap);
    }

    @PutMapping("{resource}/{id}")
    public Object updateById(@PathVariable("resource") String resource, @PathVariable("id") String id, HttpServletRequest request) {
        byte[] data;
        try {
            data = StreamUtils.copyToByteArray(request.getInputStream());
        } catch (IOException e) {
            log.error("updateById", e);
            return null;
        }
        return simpleCrudService.updateById(resource, id, data);
    }

    @DeleteMapping("{resource}/{id}")
    public Object deleteById(@PathVariable("resource") String resource, @PathVariable("id") String id) {
        return simpleCrudService.deleteById(resource, id);
    }

}
